﻿using System;
using System.Reflection;
using System.Windows.Forms;
using System.Windows.Markup;

namespace RSkor.Common.WinForms
{
    public class BindingExtension : MarkupExtension
    {
        private bool _pendingDataSource = false;
        private object _dataSource = null;
        public object DataSource
        {
            get
            {
                return _dataSource;
            }
            set
            {
                _dataSource = value;
                if (_pendingDataSource && value != null)
                {
                    (TargetObject as Control).DataBindings.Add(TargetProperty.Name,
                        DataSource, DataMember, FormattingEnabled, UpdateMode, NullValue, FormatString);
                }
            }
        }

        public string DataMember { get; set; }

        public bool FormattingEnabled { get; set; }

        public DataSourceUpdateMode UpdateMode { get; set; }

        public object NullValue { get; set; }

        public string FormatString { get; set; }

        protected object TargetObject { get; set; }

        protected PropertyInfo TargetProperty { get; set; }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget service = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
            if (service != null)
            {
                PropertyInfo pi = service.TargetProperty as PropertyInfo;
                if (pi != null && service.TargetObject is Control)
                {
                    if (DataSource == null)
                    {
                        _pendingDataSource = true;
                        TargetObject = service.TargetObject;
                        TargetProperty = pi;
                    }
                    else
                    {
                        (service.TargetObject as Control).DataBindings.Add(pi.Name,
                            DataSource, DataMember, FormattingEnabled, UpdateMode, NullValue, FormatString);
                    }
                }

            }
            return "";
        }

    }
}
